import {
  api
} from '@/api'
import router from '@/router'
import Layout from '@/components/layout'
const _import = require('../../router/_import_' + process.env.NODE_ENV)
const state = {
  promptData: '',
  isFirst: true,
  isAuth: false,
  isW7: false,
  isShowPrompt: false, // 是否显示到期提醒
  systemCopyInfo: '', // 获取微擎系统版本信息
  routes: [],
  notice_num: 0,
  police_num: 0,
  help_voice: '',
  userInfo: {},
  auth: {}
}
const getters = {
  isAuth: state => {
    return state.isAuth
  },
  isW7: state => {
    return state.isW7
  },
  routes: state => {
    return state.routes
  }
}
const mutations = {
  // 修改到期提醒数据
  changePromptData (state, item) {
    let { status } = item
    if (status === 2) {
      state.isShowPrompt = true
    } else if (status === 1 && state.isFirst) {
      state.isFirst = false
      state.isShowPrompt = true
    }
    state.promptData = item
  },
  // 修改是否显示到期提醒
  changeIsShowPrompt (state, item) {
    state.isShowPrompt = item
  },
  changeRoutesItem (state, item) {
    // console.log('changeItem ==>', item)
    let { key, val } = item
    state[key] = val
  },
  saveRoutes (state, item = []) {
    state.routes = item
    state.isAuth = true
  }
}
const actions = {
  isWeiVersion ({ commit }, obj) {
    let data = { key: 'isW7', val: obj }
    commit('changeRoutesItem', data)
  },
  getUserPromission ({
    commit
  }, obj) {
    // 正式请求接口获取路由
    api.base.getW7TmpV2().then(res => {
      if (res.code === 200) {
        let { w7tmp } = res.data
        commit('changeRoutesItem', { key: 'systemCopyInfo', val: w7tmp })
      }
    })
    api.base.getSaasAuth().then(res => {
      if (res.code === 200) {
        let allRoutes = obj.routes
        // res.data.dynamic = 0
        // employ 应用设置
        res.data.employ = res.data.h5 || res.data.app
        commit('changeRoutesItem', { key: 'auth', val: res.data })
        let authArr = ['wechat', 'h5', 'app', 'employ', 'virtual', 'reminder']
        let dynamicInd = -1
        allRoutes.map((item, index) => {
          if (item.path === '/dynamic') {
            dynamicInd = index
          }
          if (item.path === '/sys') {
            item.meta.subNavName.map(aitem => {
              aitem.url.map(bitem => {
                let authUrl = bitem.url.split('/sys/')[1]
                let authKey = authUrl.split('-')[0]
                if (authArr.includes(authKey)) {
                  bitem.auth = res.data[authKey]
                  let ind = item.children.findIndex(citem => {
                    return citem.path.includes(authKey)
                  })
                  item.children[ind].meta.auth = res.data[authKey]
                  if (authUrl === 'virtual-set') {
                    item.children[ind + 1].meta.auth = res.data[authKey]
                  }
                  if (authUrl === 'wechat') {
                    item.children[ind - 1].meta.auth = res.data[authKey]
                  }
                }
              })
            })
            let subNavName = JSON.parse(JSON.stringify(item.meta.subNavName))
            subNavName[1].url = subNavName[1].url.filter(aitem => {
              return aitem.auth
            })
            subNavName[2].url = subNavName[2].url.filter(aitem => {
              return aitem.auth
            })
            if (!res.data.wechat) {
              subNavName[0].url.splice(1, 1)
            }
            item.meta.subNavName = subNavName
            item.children = item.children.filter(aitem => {
              return aitem.meta.auth
            })
          }
        })
        if (!res.data.dynamic && dynamicInd !== -1) {
          allRoutes.splice(dynamicInd, 1)
        }
        commit('saveRoutes', allRoutes)
        let { path = '' } = obj.to
        let arr = []
        allRoutes.map(item => {
          if (item.children && item.children.length) {
            item.children.map(aitem => {
              arr.push(`${item.path}/${aitem.path}`)
            })
          }
        })
        if (!path || (path && !arr.includes(path))) {
          obj.to = allRoutes[0]
        }
        routerGo(allRoutes, obj)
      }
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}

function routerGo (routes, obj) {
  let getRouter = filterAsyncRouter(routes) // 过滤路由
  router.options.routes.push(...getRouter)
  router.addRoutes(getRouter) // 动态添加路由
  // localStorage.setItem('routes', JSON.stringify(getRouter))
  obj.next({
    ...obj.to,
    replace: true
  })
}

function filterAsyncRouter (asyncRouterMap) { // 遍历后台传来的路由字符串，转换为组件对象
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component) {
      if (route.component === 'Layout') { // Layout组件特殊处理
        route.component = Layout
      } else {
        route.component = _import(route.component)
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children)
    }
    return true
  })
  return accessedRouters
}
